/*******************************************************************************
 * ***** BEGIN LICENSE BLOCK *****
 *
 * This file is part of CCValidator.
 * Copyright 2009 Corlatti (http://www.corlatti.com.ar/)
 *
 * CCValidator is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * CCValidator is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * ***** END LICENSE BLOCK *****
 *
 * $Id: CCDateValidationRules.js 14 2009-03-28 23:07:02Z corlatti $
 * 
 * This file contains date validations rules.
 * Format check and valid dates.
 * TODO: range validations
 * 
 *******************************************************************************/
/*
 * Date format validator
 * format must be specified like this: dateformat=dd/mm/yyyy or whatever 
 * the format you like.
 * dd, mm and yyyy must be always numbers.
 * Allowed formats: ddmmyyyy - mmddyyyy - yyyymmdd - yyyyddmm
 * always with these separators . - / _ or *space*
 */
Dateformat.prototype = new CCValidationRule();
Dateformat.prototype._allowedFormat = new Array('ddmmyyyy', 'mmddyyyy', 'yyyymmdd', 'yyyyddmm');
Dateformat.prototype._regexFormatRules = new Array(
													/^\d{2}(\-|\/|\.)\d{2}\1\d{4}$/
													, /^\d{2}(\-|\/|\.)\d{2}\1\d{4}$/
													, /^\d{4}(\-|\/|\.)\d{2}\1\d{2}$/
													, /^\d{4}(\-|\/|\.)\d{2}\1\d{2}$/
												);
												
Dateformat.prototype._allowedSeparators = new Array('.','-','/','_',' ');
function Dateformat(objName, value, rule){
	var resultado = new Array(true, '');
	var msg = '';
	try {
		if(value != '' && value != null){
			var tmp = rule.split('=');
			var format = tmp[1];
			resultado = this._validateDateFormat(value, format);
		}
	} catch(e){
		throw e;
	}
	return resultado;
}

Dateformat.prototype._validateDateFormat = function(value, format){
	var resultado = new Array(true, '');
	try {
		var allowedFormat = this._checkAllowedFormat(format);
		if(!allowedFormat){
			throw 'El formato configurado:' + format + ' no es valido.';
		} else {
			resultado = this._checkDateFormat(value, format);
			if(resultado[0]){
				resultado = this._checkValidDate(value, format);
			}
		}
	} catch(e){
		throw e;
	}
	return resultado;
}

Dateformat.prototype._checkAllowedFormat = function(format){
	var resultado = false;
	try {
		//borro los separadores 
		format = this._removeSeparators(format);
		for(var i=0; i<this._allowedFormat.length; i++){
			if(format.trim() == this._allowedFormat[i]){
				resultado = true;
				break;
			}
		}
	} catch(e){
		throw e;
	}
	return resultado;
}

Dateformat.prototype._removeSeparators = function(format){
	var resultado = format;
	try {
		for(var i=0; i<this._allowedSeparators.length; i++){
			format = format.replaceAll(this._allowedSeparators[i], '');
		}
		resultado = format;
	} catch(e){
		throw e;
	}
	return resultado;
}

Dateformat.prototype._checkDateFormat = function(value, format){
	var resultado = new Array(true, '');
	try {
		for(var i=0; i<this._allowedFormat.length; i++){
			if(this._removeSeparators(format) == this._allowedFormat[i]){
				var regEx = new RegExp(this._regexFormatRules[i]);
				alert(regEx.test(value));
				if(!regEx.test(value)){
					resultado[0] = false;
					resultado[1] = "La fecha no tiene el formato correcto. " + format;
				}
			}
		}
	} catch(e){
		throw e;
	}
	return resultado;
}

Dateformat.prototype._checkValidDate = function(value, format){
	var resultado = false;
	var msg = '';
	try {
		var pattern = format;
		var day = parseInt(value.substring(pattern.indexOf("dd"),pattern.indexOf("dd")+2));
		var month = parseInt(value.substring(pattern.indexOf("mm"), pattern.indexOf("mm")+2));
		var year = parseInt(value.substring(pattern.indexOf("yyyy"),pattern.indexOf("yyyy")+4));
		
		alert(day + ' ' + month + ' ' + year);
		var daysPerMonth = { 1 : 31, 3 : 31, 
                        		4 : 30, 5 : 31,
                        		6 : 30,7 : 31,
                        		8 : 31,9 : 30,
                        		10 : 31,1 : 30,12 : 31
                        	}
        
        if(month != 2){
        		if(daysPerMonth[month] != null){
      				if(day <= daysPerMonth[month] || day != 0){
    					resultado = true;
    				}
        		}
        } else {
        	//february needs biss year check
        	if(day  == 0 || day > 28){
        		if (((day == 29) && (year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
         			resultado = true;
         		}
        	}
        }
        
        if(!resultado){
        	if(month > 12 || month < 1){
        		msg = 'El mes ingresado es incorrecto.'	
        	} else {
        		msg = 'La fecha ingresada es incorrecta. El dia no es valido para el mes.';
        	}
        }
        
		//the fucking IE needs the '/' to work
		var d = new Date(Date.parse(month + '/' + day + '/' + year));
		
	} catch(e){
		throw e;
	}
	return new Array(resultado, msg);
}




